package nettyTest.netty3Test.proxy;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.UnsupportedEncodingException;

/**
 * @Auther     : yxpweb
 * @Date       : 2021/8/14 21:37
 * @Description: 收到真是服务器的消息转发给客户端
 */
public class HexDumpProxyBackendHandler extends ChannelInboundHandlerAdapter {
	private final Channel inboundChannel;

	public HexDumpProxyBackendHandler(Channel inboundChannel) {
		this.inboundChannel = inboundChannel;
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		ctx.read();
	}

	@Override
	public void channelRead(final ChannelHandlerContext ctx, Object msg) {
		ByteBuf byteBuf = (ByteBuf) msg;
		byte[] tempByte = new byte[byteBuf.readableBytes()];
		byteBuf.readBytes(tempByte);
		try {
			String tempString = new String(tempByte, "UTF-8");
			System.out.println(tempString);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byteBuf.resetReaderIndex();
		inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) {
				if (future.isSuccess()) {
					ctx.channel().read();
				} else {
					future.channel().close();
				}
			}
		});
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) {
		HexDumpProxyFrontendHandler.closeOnFlush(inboundChannel);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		HexDumpProxyFrontendHandler.closeOnFlush(ctx.channel());
	}
}
